<template>
  <!-- 关键词高亮 -->
  <div class="brightKeyword">
    <el-form>
      <el-form-item label="关键词：">
        <el-input
          placeholder="请输入关键词"
          v-model="keyword"
          style="width: 300px; margin-right: 5px"
          @keydown.native.enter="getResult"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="result-list">
      <div
        class="result-item"
        v-for="(item,index) of result"
        :key="index"
      >
        <span
          class="title"
          v-html="item.title"
        ></span>
        <span
          class="con"
          v-html="item.con"
        ></span>
      </div>
    </div>
  </div>
</template>
              
<script>
export default {
  components: {},
  data() {
    return {
      keyword: "",
      result: []
    };
  },
  methods: {
    getResult() {
      this.result = [];
      this.listData = [
        {
          title: "初始数据",
          con: "下面是把初始数据中的每"
        },
        {
          title: "下面是把初始数据中的每一条数据",
          con:
            "下面是把初始数据中的每一条数据的四个字段分别去和输入的内容进行匹配每"
        }
      ];

      //遍历数据，找出包含keyword的数据
      this.listData.forEach(item => {
        if (
          item.title.indexOf(this.keyword) !== -1 ||
          item.con.indexOf(this.keyword) !== -1
        ) {
          this.result.push(item);
        }
      });

      //高亮处理
      this.result.map(item => {
        item.title = this.brightKeyword(item.title);
        item.con = this.brightKeyword(item.con);
      });
    },

    //关键词高亮
    brightKeyword(val) {
      let search = this.keyword;
      //将包含keyword的内容替换成高亮的html
      if (val.indexOf(search) !== -1) {
        return val.replace(search, `<font color='#f80808'>${search}</font>`);
      } else {
        return val;
      }
    }
  },
  created() {}
};
</script>
              
<style lang="scss" scoped>
.brightKeyword {
  text-align: left;
  .result-item {
    margin-bottom: 15px;
    span {
      display: block;
    }
    .title {
      font-weight: bold;
    }
  }
}
</style>